package com.eunion.web.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eunion.core.exception.ProjectException;
import com.eunion.web.admin.entity.AdminUser;
import com.eunion.web.admin.entity.AdminUserRole;
import com.eunion.web.admin.repository.AdminUserRepository;
import com.eunion.web.admin.repository.AdminUserRoleRepository;
import com.eunion.web.admin.service.AdminUserService;
import com.eunion.web.common.base.BaseRepository;
import com.eunion.web.common.base.impl.BaseServiceImpl;

/**
 */
@Service(value = "adminUserService")
@Transactional
public class AdminUserServiceImpl extends BaseServiceImpl<AdminUser, String> implements AdminUserService {

    @Resource
    private AdminUserRepository adminUserRepository;

    @Resource
    private AdminUserRoleRepository adminUserRoleRepository;

    @Override
    public BaseRepository<AdminUser, String> geBaseRepository() {
        return adminUserRepository;
    }

    @Override
    public AdminUser findOneByUserNameAndPassword(String username, String password) {
        return adminUserRepository.findOneByUsernameAndPassword(username, password);
    }

    @Override
    public AdminUser findOneByUsername(String username) {
        try {
            return adminUserRepository.findOneByUsername(username);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public int resetPassword(String username) {
        return adminUserRepository.resetPassword(username);
    }

    @Override
    public int updatePassword(String newPwd, String username, String password) {
        return adminUserRepository.updatePassword(newPwd, username, password);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int removeUserRoles(String username, String[] roleCodes) {
        Integer sums = adminUserRoleRepository.removeUserRoles(username);
        List<AdminUserRole> araLists = new ArrayList<AdminUserRole>();
        for (String roleCode : roleCodes) {
            araLists.add(new AdminUserRole(roleCode, username));
        }
        List<AdminUserRole> returnSaves = adminUserRoleRepository.save(araLists);
        if (sums != null && returnSaves != null) {
            return 1;
        }

        throw new ProjectException("数据更新失败，请检查数据合法性.");
    }
}
